package com.akuhome.resource.handle;

import com.akuhome.resource.entity.Result;
import com.akuhome.resource.enums.ResultEnum;
import com.akuhome.resource.exception.ResourceException;
import com.akuhome.resource.util.ResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

@ControllerAdvice
public class ExceptionHandle {

    private final static Logger logger = LoggerFactory.getLogger(ExceptionHandle.class);

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result<Object> Exception(Exception e){
        if(e instanceof ResourceException) {
            return ResultUtil.error((ResourceException) e);
        }else{
            logger.error("\n---[系统异常]---\n{}",e.toString());
            return ResultUtil.error(new ResourceException(ResultEnum.UNKNOWN_ERROR));
        }
    }

    @ExceptionHandler(value = MethodArgumentTypeMismatchException.class)
    @ResponseBody
    public Result<Object> MethodArgumentTypeMismatchException(Exception e){
        if(e instanceof MethodArgumentTypeMismatchException){
            return ResultUtil.error(new ResourceException(ResultEnum.ARG_MISMATCH_ERROR));
        }else{
            logger.error("\n---[系统异常]---\n{}",e.toString());
            return ResultUtil.error(new ResourceException(ResultEnum.UNKNOWN_ERROR));
        }
    }

    @ExceptionHandler(value = HttpRequestMethodNotSupportedException.class)
    @ResponseBody
    public Result<Object> HttpRequestMethodNotSupportedException(Exception e){
        if(e instanceof HttpRequestMethodNotSupportedException) {
            return ResultUtil.error(new ResourceException(ResultEnum.METHOD_NOT_SUPPORT_ERROR));
        }else{
            logger.error("\n---[系统异常]---\n{}",e.toString());
            return ResultUtil.error(new ResourceException(ResultEnum.UNKNOWN_ERROR));
        }
    }
}
